import 'dart:convert';

import 'package:winkai/ext/ext.dart';
import 'package:winkai/generated/json/base/json_field.dart';
import 'package:winkai/generated/json/vip_product_info.g.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

export 'package:winkai/generated/json/vip_product_info.g.dart';

@JsonSerializable()
class VipProductInfo {
  String name = "";
  String productId = "";
  String price = "";
  double rawPrice = 0;
  String currencyCode = "";
  String currencySymbol = "";
  String saveRate = "";
  String hourPrice = "";
  bool isYear = false;

  VipProductInfo();

  factory VipProductInfo.fromJson(Map<String, dynamic> json) =>
      $VipProductInfoFromJson(json);

  factory VipProductInfo.fromProduct(ProductDetails details) {
    bool isYear = false;
    if (details is AppStoreProductDetails) {
      isYear = details.skProduct.subscriptionPeriod?.unit ==
          SKSubscriptionPeriodUnit.year;
    }
    String currencySymbol;
    String rate;
    if (isYear) {
      currencySymbol =
          '${details.currencySymbol}${numFixed(details.rawPrice / 365 / 24, position: 3)}';
      rate = '76%';
    } else {
      currencySymbol =
          '${details.currencySymbol}${numFixed(details.rawPrice / 30 / 24, position: 3)}';
      rate = '';
    }
    var info = VipProductInfo()
      ..productId = details.id
      ..name = details.title
      ..price = details.price
      ..rawPrice = details.rawPrice
      ..currencyCode = details.currencyCode
      ..currencySymbol = details.currencySymbol
      ..saveRate = rate
      ..hourPrice = currencySymbol
      ..isYear = isYear;

    return info;
  }

  Map<String, dynamic> toJson() => $VipProductInfoToJson(this);

  @override
  String toString() {
    return jsonEncode(this);
  }
}
